<template>
  <div
    style="
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
    "
  >
    <div
      style="
        width: 350px;
        background-color: bisque;
        border-radius: 5px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        display: flex;
        justify-content: center;
        padding: 20px;
      "
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
        <div
          style="
            margin-bottom: 40px;
            text-align: center;
            font-size: bold;
            font-size: 16px;
          "
        >
          <h2 style="color: cadetblue">英语练习系统</h2>
        </div>
        <el-form-item label="email" prop="userEmail">
          <el-input
            v-model="form.userEmail"
            style="width: 240px"
            placeholder="Please input email"
            size="large"
        /></el-form-item>
        <el-form-item label="password" prop="password">
          <el-input
            v-model="form.password"
            style="width: 240px"
            type="password"
            placeholder="Please input password"
            show-password
            size="large"
        /></el-form-item>
        <div>
          <el-button
            type="primary"
            size="large"
            style="width: 100%"
            @click="submitForm(formRef)"
            >登录</el-button
          >
        </div>
        <div style="text-align: right; padding-top: 10px">
          还没有账号?请<a style="color: cadetblue" href="/register">注册</a>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import qs from "qs";
import { useAuthStore } from "@/stores/auth";
import { httpClient } from "@/libs/http-client";
import router from "@/router";
import { useRoute } from "vue-router";

const route = useRoute();
onMounted(() => {
  const emailFromQuery = route.query.email as string;
  if (emailFromQuery) {
    form.userEmail = emailFromQuery;
  }
});
const form = reactive({
  userEmail: "",
  password: "",
});

const formRef = ref<FormInstance>();

interface RuleForm {
  userEmail: string;
  password: string;
}

const ruleForm = reactive({
  userEmail: "",
  password: "",
});
const rules = reactive<FormRules<RuleForm>>({
  userEmail: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
});
type LoginResponse = {
  token: string;
};
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      console.log("登录!");
      const data = qs.parse(form);
      httpClient
        .post<LoginResponse>("/start/login", data)
        .then((loginData) => {
          // loginData 已经是 data 字段内容
          console.log("登录成功:", loginData);
          const authStore = useAuthStore();
          // token前面插入Bearer
          loginData.token = "Bearer " + loginData.token;
          authStore.setToken(loginData.token);
          // 跳转到主页
          router.push("/dialogue");
        })
        .catch((error) => {
          console.error("登录失败:", error);
          // 显示具体错误提示（根据 error.code 处理）
          if (error.code === 401) {
            ElMessage("登录已过期，请重新登录");
          } else {
            ElMessage(`请求失败: ${error.message}`);
          }
        });
    } else {
      console.log("error submit!");
    }
  });
};
</script>

<style>
</style>
